<template>
  <common-edit-dialog
    :title="dialogTitle"
    :visible.sync="dialogShow"
    :button-loading="loading"
    @cancel="close('onlyClose')"
    @submit="submitForm"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="80px"
      @submit.native.prevent
    >
      <el-row :gutter="18">
        <el-col :span="12">
          <el-form-item label="用户名" prop="userName">
            <common-input
              v-model.trim="form.userName"
              :type="'text'"
              :disabled="!!form.userId"
              placeholder="请输入"
              :maxlength="16"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="姓名" prop="nickName">
            <common-input
              v-model="form.nickName"
              :type="'text'"
              placeholder="请输入"
              :maxlength="6"
              :verify="true"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="所属角色" class="role-list" prop="roleIds">
            <el-select
              v-model="form.roleIds"
              ref="roleSel"
              multiple
              filterable
              placeholder="请选择"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="(item, index) in roleSelectArr"
                :key="index"
                :label="item.roleName"
                :value="item.roleId"
                :disabled="form.userId && !item.freeze"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <!--        <el-col :span="24">-->
        <!--          <el-form-item label="数据权限" class="role-list" prop="permissionIds">-->
        <!--            <el-select-->
        <!--              v-model="form.permissionIds"-->
        <!--              ref="permissionSelect"-->
        <!--              filterable-->
        <!--              multiple-->
        <!--              placeholder="请选择"-->
        <!--              clearable-->
        <!--              style="width: 100%"-->
        <!--            >-->
        <!--              <el-option-->
        <!--                v-for="(item, index) in authSelectArr"-->
        <!--                :key="index"-->
        <!--                :label="item.permissionName"-->
        <!--                :value="item.permissionId"-->
        <!--                class="item-icon"-->
        <!--                :disabled="form.userId && !item.freeze"-->
        <!--              >-->
        <!--              </el-option>-->
        <!--            </el-select>-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->
        <el-col :span="24">
          <el-form-item label="所属组织" prop="deptIdArr">
            <treeselect
              :disabled="isEdit"
              :searchable="false"
              :options="deptSelectArr"
              placeholder="请选择"
              v-model="form.deptIdArr"
              noResultsText="无数据"
              @open="notOpen"
              :style="{
                '--theme-color': systemInfo.theme,
              }"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号码" prop="phonenumber">
            <div style="position: relative">
              <common-input
                v-model="form.phonenumber"
                ref="numberInput"
                @focus="focusPhoneNumber('number')"
                @blur="blurPhoneNumber('number')"
                placeholder="请输入"
              />
              <span
                class="initNumber"
                v-if="isShowNumber"
                @click="hiddenData('number')"
                >{{ showEncodeData("number", form.phonenumber) }}</span
              >
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="身份证号" prop="identityCard">
            <div style="position: relative">
              <common-input
                v-model="form.identityCard"
                ref="idCardInput"
                @focus="focusPhoneNumber('idCard')"
                @blur="blurPhoneNumber('idCard')"
                placeholder="请输入"
              />
              <span
                class="initNumber"
                v-if="isShowIDCard"
                @click="hiddenData('idCard')"
                >{{ showEncodeData("idCard", form.identityCard) }}</span
              >
            </div>
          </el-form-item>
        </el-col>
        <!--<el-col :span="12">
          <el-form-item label="生效日期" prop="effTime">
            <el-date-picker v-model="form.effTime" type="date" placeholder="请选择" value-format="yyyy-MM-dd"
              format="yyyy-MM-dd"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="失效日期" prop="expTime">
            <el-date-picker v-model="form.expTime" type="date" placeholder="请选择" value-format="yyyy-MM-dd"
              format="yyyy-MM-dd"></el-date-picker>
          </el-form-item>
        </el-col>-->

        <el-col :span="12">
          <el-form-item label="邮箱" prop="email">
            <div style="position: relative">
              <common-input
                v-model="form.email"
                ref="emailInput"
                :verify="false"
                @focus="focusPhoneNumber('email')"
                @blur="blurPhoneNumber('email')"
                placeholder="请输入"
              />
              <span
                class="initNumber"
                v-if="isShowEmail"
                @click="hiddenData('email')"
                >{{ showEncodeData("email", form.email) }}</span
              >
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="辅助策略" prop="userSecondaryLoginPolicyId">
            <el-select
              v-model="form.userSecondaryLoginPolicyId"
              placeholder="请选择"
              ref="select"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="(item, index) in loginPolicySelect"
                :key="index"
                :label="item.policyName"
                :value="item.policyType"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="!form.userId">
          <el-form-item label="密码" prop="genPwdWay">
            <el-radio v-model="form.genPwdWay" label="1">默认密码</el-radio>
            <el-radio v-model="form.genPwdWay" label="2">随机密码</el-radio>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="性别" prop="sex">
            <el-radio v-model="form.sex" label="0">男</el-radio>
            <el-radio v-model="form.sex" label="1">女</el-radio>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="备注">
            <common-input
              :verify="true"
              type="textarea"
              :autosize="{ minRows: 4, maxRows: 8 }"
              v-model="form.remark"
              placeholder="请输入"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </common-edit-dialog>
</template>

<script>
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {
  dept_select,
  role_select,
  loginpolicy_select,
  user_duration,
  user_add,
  user_edit,
  user_info,
} from "@/api/management/usercenter/user.js";
import { idNumberRule, emailRule, phoneNumberRule } from "@/utils/formRules";
import { decode, encode } from "@/utils/aesUtils";
import Utils from "@/utils";
import HandleTips from "@/mixins/modules/HandleTips";
import { mapGetters } from "vuex";

export default {
  components: { Treeselect },
  props: {
    deptSelect: {
      type: Array,
      default: () => [],
    },
    roleSelect: {
      type: Array,
      default: () => [],
    },
    loginPolicySelect: {
      type: Array,
      default: () => [],
    },
    authSelect: {
      type: Array,
      default: () => [],
    },
    userDuration: {
      type: Number,
      default: 0,
    },
  },
  mixins: [HandleTips],
  data() {
    return {
      // valueConsistsOf: 'LEAF_PRIORITY',
      valueConsistsOf: "ALL",
      dialogTitle: "新增用户", // 标题
      dialogShow: false, // 是否显示
      isEditPhone: false,
      isEditIdentity: false,
      isEditEmail: false,
      form: {
        userName: "",
        nickName: "",
        sex: "0",
        genPwdWay: "1",
        phonenumber: "",
        deptIdArr: [],
        oldPhonenumber: "",
        identityCard: "",
        email: "",
        oldEmail: "",
        permissionIds: [],
        roleIds: [],
        userSecondaryLoginPolicyId: null,
        remark: "",
      },
      rules: {
        userName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        nickName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        deptIdArr: [
          { required: true, message: "请选择所属组织", trigger: "blur" },
        ],
        roleIds: [
          { required: true, message: "请选择所属角色", trigger: "blur" },
        ],
        permissionIds: [
          { required: true, message: "请选择数据权限", trigger: "blur" },
        ],
        effTime: [
          { required: true, message: "请输入有生效日期", trigger: "blur" },
        ],
        expTime: [
          { required: true, message: "请输入有失效日期", trigger: "blur" },
        ],
        phonenumber: phoneNumberRule,
        // identityCard: idNumberRule,
        userSecondaryLoginPolicyId: [
          { required: true, message: "请选择辅助策略", trigger: "blur" },
        ],
        email: emailRule,
      },
      radio: "1",
      treeValue: [],
      // deptSelect: [],
      // roleSelect: [],
      // loginPolicySelect: [],
      // expDuration: 0,
      isShowNumber: true,
      decodeNumber: "",
      isShowIDCard: true,
      decodeIDCard: "",
      isShowEmail: true,
      decodeEmail: "",
      loading: false,
      authSelectArr: [],
      roleSelectArr: [],
      deptSelectArr: [],
      isEdit: false,
    };
  },
  computed: {
    ...mapGetters(["systemInfo", "department"]),
  },
  methods: {
    notOpen() {
      // console.log(this.$refs.select);
      // console.log(this.$refs.sel);
      this.$refs.select.blur();
      this.$refs.roleSel.blur();
      // this.$refs.permissionSelect.blur();
    },
    /**
     * 关闭
     */
    close(onlyClose) {
      this.$refs.form.resetFields();
      this.dialogShow = false;
      this.form = {
        userName: "",
        nickName: "",
        sex: "0",
        genPwdWay: "1",
        phonenumber: "",
        deptIdArr: [],
        oldPhonenumber: "",
        identityCard: "",
        email: "",
        oldEmail: "",
        permissionIds: [],
        roleIds: [],
        userSecondaryLoginPolicyId: null,
        remark: "",
      };
      if (!onlyClose) {
        this.$emit("refresh");
      }
    },

    /**
     * 显示
     */
    show(data) {
      this.isEdit = !!data.userId;
      this.dialogTitle = data.userId ? "编辑用户" : "新增用户";
      this.isShowNumber = !!data.userId;
      this.isShowIDCard = !!data.userId;
      this.isShowEmail = !!data.userId;

      if (data && data.userId) {
        this.getUserInfo(data);
      } else {
        this.roleSelectArr = this.roleSelect;
        this.authSelectArr = this.authSelect;
        this.deptSelectArr = this.deptSelect;
        this.form.deptIdArr = this.department
          ? this.department
          : data.deptId && data.deptId.length
          ? [data.deptId]
          : null;
        this.setDisabled(this.deptSelectArr);
      }
      this.$nextTick(() => {
        this.dialogShow = true;
      });
    },

    // //组织下拉选择
    // getDeptSelect() {
    //   dept_select({}).then((res) => {
    //     this.deptSelect = res.data
    //   })
    // },
    // //角色下拉选择
    // getRoleSelect() {
    //   role_select({}).then((res) => {
    //     this.roleSelect = res.data
    //   })
    // },
    // //登录辅助下拉选择
    // getPolicySelect() {
    //   loginpolicy_select({}).then((res) => {
    //     this.loginPolicySelect = res.data
    //   })
    // },
    // //用户有效期
    // getDurationSelect() {
    //   user_duration({}).then((res) => {
    //     this.expDuration = parseInt(res.msg)
    //   })
    // },
    setDisabled(data) {
      if (data.length > 0) {
        data.forEach((f) => {
          f.isDisabled = f.freeze !== "N";
          if (f.children && f.children.length > 0) this.setDisabled(f.children);
        });
      }
    },
    getUserInfo(info) {
      this.form.userId = info.userId;
      user_info({ userId: this.form.userId })
        .then((res) => this.handleEditTips(res))
        .then((res) => {
          if (res && res.code === 200) {
            this.authSelectArr = res.data.loginUserPermissions;
            this.roleSelectArr = res.data.loginUserRoles;
            this.deptSelectArr = res.data.loginUserDepts;
            this.setDisabled(this.deptSelectArr);

            const data = res.data.userDeatailVo.user;
            this.form.userName = data.userName;
            this.form.nickName = data.nickName;
            this.form.remark = data.remark;
            //角色
            this.form.roleIds =
              data && data.roleIds && data.roleIds.length
                ? data.roleIds.map(String)
                : [];
            //部门
            this.form.deptIdArr =
              data && data.deptIdArr && data.deptIdArr.length
                ? data.deptIdArr.map(String)
                : [];
            this.form.permissionIds =
              data.permissionIds && data.permissionIds.length
                ? data.permissionIds.map(String)
                : [];
            this.form.identityCard = data.identityCard;
            this.form.sex = data.sex;
            this.form.userSecondaryLoginPolicyId =
              data.userSecondaryLoginPolicyId;

            //手机号解密加*展示
            this.isShowNumber = !!data.phonenumber;
            this.form.phonenumber = data.phonenumber
              ? decode(data.phonenumber)
              : "";
            this.form.oldPhonenumber = data.phonenumber
              ? decode(data.phonenumber)
              : "";
            // this.decodeNumber = data.phonenumber ? Utils.phoneEncryption(decode(data.phonenumber)) : ''

            //身份证解密加*展示
            this.isShowIDCard = !!data.identityCard;
            this.form.identityCard = data.identityCard
              ? decode(data.identityCard)
              : "";
            this.form.oldIdentity = data.identityCard
              ? decode(data.identityCard)
              : "";
            // this.decodeIDCard = data.identityCard ? Utils.identityEncryption(decode(data.identityCard)) : ''

            //邮箱解密加*展示
            this.isShowEmail = !!data.email;
            this.form.email = data.email ? decode(data.email) : "";
            this.form.oldEmail = data.email ? decode(data.email) : "";
            // this.decodeEmail = data.email ? Utils.emailEncryption(decode(data.email)) : ''
          } else {
            this.$GlobalErrorConfirm(
              "获取用户信息失败",
              res.msg,
              "重新加载"
            ).then(() => {
              this.getUserInfo();
            });
          }
        });
    },
    // phoneBlur() {
    //   this.isEditEmail = !this.form.email
    // },
    // phoneFocus() {
    //   this.isEditEmail = !this.form.email
    // },
    /**
     * 提交
     */
    submitForm() {
      this.$nextTick(() => {
        this.$refs["form"].validate((valid) => {
          if (valid) {
            //.map(String),整型数组转字符串数组
            if (this.form.deptIdArr instanceof Array) {
              this.form.deptIdArr = this.form.deptIdArr.map(String);
            } else {
              this.form.deptIdArr = this.form.deptIdArr.split(",");
            }

            this.form.deptIds = this.form.deptIdArr.join(",");
            this.form.expDuration = this.expDuration;

            this.form.roleNamesForLog = this.getItemNames(
              this.form.roleIds,
              this.roleSelectArr,
              "roleId",
              "roleName"
            );
            this.form.permissionNamesForLog = this.getItemNames(
              this.form.permissionIds,
              this.authSelectArr,
              "permissionId",
              "permissionName"
            );
            this.form.deptFullNamesForLog = this.getTreeNodeNames(
              this.form.deptIdArr,
              this.deptSelectArr
            );

            if (!!this.form.userId) {
              let params = {
                ...this.form,
                phonenumber: encode(this.form.phonenumber),
                identityCard: encode(this.form.identityCard),
                email: this.form.email ? encode(this.form.email) : "",
              };
              this.loading = true;
              delete params.oldEmail;
              delete params.oldIdentity;
              delete params.oldPhonenumber;
              delete params.phone;
              user_edit(params)
                .then((res) => {
                  if (res && res.code === 200) {
                    this.$GlobalSuccessMessage("编辑成功");
                    this.close();
                  } else {
                    this.$GlobalErrorConfirm("编辑失败", res.msg).then();
                  }
                })
                .finally(() => (this.loading = false));
            } else {
              let params = {
                ...this.form,
                phonenumber: encode(this.form.phonenumber),
                identityCard: encode(this.form.identityCard),
                email: this.form.email ? encode(this.form.email) : "",
              };

              this.loading = true;
              user_add(params)
                .then((res) => {
                  if (res && res.code === 200) {
                    this.$GlobalSuccessMessage("新增成功");
                    this.close();
                  } else {
                    this.$GlobalErrorConfirm("新增失败", res.msg).then();
                  }
                })
                .finally(() => (this.loading = false));
            }
          }
        });
      });
    },
    /**
     * input聚焦时事件
     */
    focusPhoneNumber(type) {
      if (
        type === "number" &&
        this.form.phonenumber === this.form.oldPhonenumber
      ) {
        this.form.phonenumber = "";
        this.isShowNumber = false;
      } else if (
        type === "idCard" &&
        this.form.identityCard === this.form.oldIdentity
      ) {
        this.form.identityCard = "";
        this.isShowIDCard = false;
      } else if (type === "email" && this.form.email === this.form.oldEmail) {
        this.form.email = "";
        this.isShowEmail = false;
      }
    },

    hiddenData(type) {
      if (type === "number") {
        this.isShowNumber = false;
        this.$refs.numberInput.$refs.input.focus();
      } else if (type === "idCard") {
        this.isShowIDCard = false;
        this.$refs.idCardInput.$refs.input.focus();
      } else if (type === "email") {
        this.isShowEmail = false;
        this.$refs.emailInput.$refs.input.focus();
      }
    },
    /**
     * input失焦时事件
     */
    blurPhoneNumber(type) {
      if (type === "number") {
        if (!this.form.phonenumber && this.form.oldPhonenumber) {
          this.isShowNumber = true;
          this.form.phonenumber = this.form.oldPhonenumber;
        } else {
          this.isShowNumber = false;
        }
      } else if (type === "idCard") {
        if (!this.form.identityCard && this.form.oldIdentity) {
          this.isShowIDCard = false;
          // this.form.identityCard = this.form.oldIdentity;
          this.form.identityCard = "";
        } else {
          this.isShowIDCard = false;
        }
      } else if (type === "email") {
        if (!this.form.email && this.form.oldEmail) {
          this.isShowEmail = true;
          this.form.email = this.form.oldEmail;
        } else {
          this.isShowEmail = false;
        }
      }
    },
    /**
     * 根据类型设置加密显示
     */
    showEncodeData(type, data) {
      if (data) {
        if (type === "number") {
          return Utils.phoneEncryption(data);
        } else if (type === "idCard") {
          return Utils.identityEncryption(data);
        } else if (type === "email") {
          return Utils.emailEncryption(data);
        }
      }
    },

    /**
     * 获取对应数组中的对应的key值
     * @param dataArr 选中的数据的集合
     * @param optionArr 所有数据集合
     * @param dataKey
     * @param key
     */
    getItemNames(dataArr, optionArr, dataKey, key) {
      let list = [];
      if (dataArr.length && optionArr.length) {
        dataArr.forEach((f) => {
          let index = optionArr.findIndex(
            (v) => v[dataKey].toString() === f.toString()
          );
          if (index > -1) {
            list.push(optionArr[index][key]);
          }
        });
      }
      return list.join(",");
    },

    /**
     * 获取对应树结构中的对应的key值
     * @param dataArr 选中的数据的集合
     * @param treeArr 所有数据集合
     * @param dataKey
     * @param key
     */
    getTreeNodeNames(dataArr, treeArr, dataKey, key) {
      let list = [];
      if (dataArr.length && treeArr.length) {
        dataArr.forEach((f) => {
          let getTreeName = (data) => {
            data.forEach((v) => {
              if (v.id.toString() === f.toString()) {
                list.push(v.label);
              } else {
                if (v.children && v.children.length) {
                  getTreeName(v.children);
                }
              }
            });
          };
          getTreeName(treeArr);
        });
      }
      return list.join(",");
    },
  },
  created() {
    // this.getDeptSelect()
    // this.getRoleSelect()
    // this.getPolicySelect()
    // this.getDurationSelect()
  },
  mounted() {
    this.resetForm("form");
  },
};
</script>
<style lang="scss" scoped>
.tree {
  height: calc(100% - 56px);

  .el-dropdown-link {
    display: inline-block;
    width: 100%;
  }

  ::v-deep {
    .el-dropdown {
      width: 100% !important;
    }
  }
}

.initNumber {
  position: absolute;
  top: 3px;
  left: 16px;
  background-color: #fff;
  height: 28px;
  line-height: 28px;
  font-size: 13px;
  width: calc(100% - 32px);

  &:hover {
    cursor: text;
  }
}

.role-list {
  ::v-deep .el-select {
    .el-tag {
      .el-tag__close {
        color: #fff;
        margin-right: 3px;
      }
    }
  }
}

::v-deep .vue-treeselect__control {
  .vue-treeselect__x-container {
    display: none;
  }

  &:hover {
    //&代表上级的.vue-treeselect__control
    .vue-treeselect__x-container {
      display: table-cell;
    }
  }

  padding-left: 0;

  .vue-treeselect__placeholder {
    margin-left: 10px;
  }

  .vue-treeselect__single-value {
    padding-left: 10px;
  }

  .vue-treeselect__multi-value {
    margin-bottom: 0;
    padding: 2px 0;

    .vue-treeselect__multi-value-item-container {
      line-height: 19px;
      font-size: 12px;
      margin: 2px 0 2px 6px;
      padding: 0;
    }

    .vue-treeselect__multi-value-item {
      background-color: #f4f4f5;
      border-color: #e9e9eb;
      color: #909399;
      display: flex;
      align-items: center;
      padding-right: 1px;

      .vue-treeselect__value-remove {
        width: 12px !important;
        height: 12px !important;
        margin-right: 3px;
        color: #fff;
        border-left: none;
        background-color: #c0c4cc;
        border-radius: 50%;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 0;

        &:hover {
          background-color: #909399;
        }
      }
    }
  }
}

::v-deep
  .vue-treeselect--focused:not(.vue-treeselect--open)
  .vue-treeselect__control {
  border-color: var(--theme-color) !important;
  box-shadow: none;
}
</style>
